import React from 'react';
import ReactDOM from 'react-dom';
import { message, Progress } from 'antd';
import { getUpgradeState, getUpgradeUpdate } from '@api/update';
import { getCert } from '@api/cert';
import UpgradingImg from './images/upgrading.png';
import { UPDATING_STAGE_PROCESS_MAP, MAX_UPDATING_ERROR_TIMES } from '@util/constants';
import _ from 'lodash';
import setOem from '@util/set-oem';
import './index.less';

class Updating extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      status: 'active',
      upgradeProcess: 0,
      desc: '请稍后，网站正在飞速升级中…',
      isCluster: false
    };
    this.errorTimes = 0;
    this.pollTimer = null;
  }
  componentDidMount() {
    this.pollStatus();
    this.initByOemState();
  }

  initByOemState = () => {
    getCert().then(r => {
      this.setState({ isCluster: r.is_cluster || false });
      setOem(r);
    });
  };

  // 集群请求的升级
  getUpgradeUpdate = () => {
    getUpgradeUpdate()
      .then(res => {
        const data = _.get(res, 'data', []);
        let item = data.find(r => r.role === 'master');
        if (!item) {
          return;
        }
        let stage = _.get(item, 'stage');
        let expire = Number(_.get(item, 'expire', 0)) * 1000;
        let status = _.get(item, 'status');
        if (!status) {
          if (expire < Date.now()) {
            this.errorTimes++;
          } else {
            this.errorTimes = 0;
          }
          if (this.errorTimes > MAX_UPDATING_ERROR_TIMES) {
            status = 'fail';
          } else if (this.errorTimes) {
            return;
          }
        }
        if (status === 'success') {
          // 升级成功
          this.setState({
            upgradeProcess: 100
          });
          message.success('升级成功!');
          window.clearInterval(this.pollTimer);
          setTimeout(() => {
            this.setState({ upgrading: false });
            window.location.reload();
          }, 3000);
        } else if (status === 'failed') {
          // 升级失败
          window.clearInterval(this.pollTimer);
          this.setState({
            upgradeProcess: 100,
            failModalVisible: true,
            upgrading: false
          });
          window.clearInterval(this.pollTimer);
        } else if (UPDATING_STAGE_PROCESS_MAP[stage]) {
          this.setState({
            upgradeProcess: UPDATING_STAGE_PROCESS_MAP[stage]
          });
        }
      })
      .catch(error => {
        this.errorTimes++;
        if (this.errorTimes > MAX_UPDATING_ERROR_TIMES) {
          // 升级失败
          this.setState({
            upgradeProcess: 100,
            status: 'exception',
            upgrading: false,
            desc: '升级失败!'
          });
          window.clearInterval(this.pollTimer);
        }
        window.console.log(error);
      });
  };

  // 集群请求的升级
  getUpgradeUpdate = () => {
    getUpgradeUpdate()
      .then(res => {
        const data = _.get(res, 'data', []);
        let item = data.find(r => r.role === 'master');
        if (!item) {
          return;
        }
        let stage = _.get(item, 'stage');
        let expire = Number(_.get(item, 'expire', 0)) * 1000;
        let status = _.get(item, 'status');
        if (!status) {
          if (expire < Date.now()) {
            this.errorTimes++;
          } else {
            this.errorTimes = 0;
          }
          if (this.errorTimes > MAX_UPDATING_ERROR_TIMES) {
            status = 'fail';
          } else if (this.errorTimes) {
            return;
          }
        }
        if (status === 'success') {
          // 升级成功
          this.setState({
            upgradeProcess: 100
          });
          message.success('升级成功!');
          window.clearInterval(this.pollTimer);
          setTimeout(() => {
            this.setState({ upgrading: false });
            window.location.reload();
          }, 3000);
        } else if (status === 'failed') {
          // 升级失败
          window.clearInterval(this.pollTimer);
          this.setState({
            upgradeProcess: 100,
            failModalVisible: true,
            upgrading: false
          });
          window.clearInterval(this.pollTimer);
        } else if (UPDATING_STAGE_PROCESS_MAP[stage]) {
          this.setState({
            upgradeProcess: UPDATING_STAGE_PROCESS_MAP[stage]
          });
        }
      })
      .catch(error => {
        this.errorTimes++;
        if (this.errorTimes > MAX_UPDATING_ERROR_TIMES) {
          // 升级失败
          this.setState({
            upgradeProcess: 100,
            status: 'exception',
            upgrading: false,
            desc: '升级失败!'
          });
          window.clearInterval(this.pollTimer);
        }
        window.console.log(error);
      });
  };

  getUpgradeState = () => {
    if (this.setState.isCluster) {
      getUpgradeUpdate();
      return;
    }
    getUpgradeState()
      .then(res => {
        let stage = _.get(res, 'data.stage');
        let expire = Number(_.get(res, 'data.expire', 0)) * 1000;
        let status = _.get(res, 'data.status');
        if (!status) {
          if (expire < Date.now()) {
            this.errorTimes++;
          } else {
            this.errorTimes = 0;
          }
          if (this.errorTimes > MAX_UPDATING_ERROR_TIMES) {
            status = 'fail';
          } else if (this.errorTimes) {
            return;
          }
        }
        if (status === 'success') {
          // 升级成功
          this.setState({
            upgradeProcess: 100,
            upgrading: false,
            status: 'success',
            desc: '升级成功!'
          });
          message.success('升级成功!');
          window.clearInterval(this.pollTimer);
          window.location.reload();
        } else if (status === 'failed') {
          // 升级失败
          this.setState({
            upgradeProcess: 100,
            status: 'exception',
            upgrading: false,
            desc: '升级失败!'
          });
          window.clearInterval(this.pollTimer);
        } else if (UPDATING_STAGE_PROCESS_MAP[stage]) {
          this.setState({
            upgradeProcess: UPDATING_STAGE_PROCESS_MAP[stage]
          });
        }
      })
      .catch(error => {
        this.errorTimes++;
        if (this.errorTimes > MAX_UPDATING_ERROR_TIMES) {
          // 升级失败
          this.setState({
            upgradeProcess: 100,
            status: 'exception',
            upgrading: false,
            desc: '升级失败!'
          });
          window.clearInterval(this.pollTimer);
        }
        window.console.log(error);
      });
  };

  pollStatus() {
    this.pollTimer = window.setInterval(this.getUpgradeState, 10000);
  }
  render() {
    const { upgradeProcess, status, desc } = this.state;
    return (
      <div className="upgrating">
        <div className="content">
          <img src={UpgradingImg} className="upgrading-img" />
          <Progress
            percent={upgradeProcess}
            style={{ width: 260, marginLeft: 16 }}
            status={status}
          />
          <p className="desc">{desc}</p>
        </div>
      </div>
    );
  }
}

// eslint-disable-next-line react/no-deprecated
ReactDOM.render(<Updating />, document.getElementById('root'));
